//
//  MomentsWidget.swift
//  WidgetExample
//
//  Created by Ben on 2022/4/10.
//  Copyright © 2022 Ben. All rights reserved.
//

import WidgetKit
import SwiftUI
import Intents

class UserModel: Identifiable {
    
    init(name: String, handle: String, moments: String, start: Int, time: String) {
        self.name = name
        self.handle = handle
        self.moments = moments
        self.start = start
        self.time = time
    }
    
    let id: String = UUID().uuidString
    let name: String
    let handle: String
    let moments: String
    let start: Int
    let time: String
    
    var handleImage: UIImage?
}

let DEFAULT_USER_LIST: [UserModel] = [
    UserModel(name: "亚托克斯激情岁月", handle: "https://img2.baidu.com/it/u=2254334584,1444549882&fm=253&fmt=auto&app=138&f=JPEG?w=308&h=308", moments: "我曾触摸过星辰，曾见证过数千个太阳的光芒，如今我被这优雅蒙蔽了双眼。", start: 463, time: "12:39"),
    UserModel(name: "扣你鸡娃", handle: "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F56%2Fdc%2F48%2F56dc489d1c22bb4a96a5cfdb15a2ff57.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652347654&t=1b3007f0a873e60f5630673c5698ef6f", moments: "今天排位10连跪😂", start: 2394, time: "12:39"),
    UserModel(name: "赛博朋克007", handle: "https://img2.baidu.com/it/u=1672275024,2080481161&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750", moments: "“你以为你骗过了死神？但其实死神欺骗了你。”在夜之城，命运几乎无法改变。愤怒吗？愤怒就去反抗，去把一切烧成灰。", start: 28131, time: "12:39"),
    
    UserModel(name: "真相只有一个", handle: "https://img2.baidu.com/it/u=750545161,580821559&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=501", moments: "新机子哇椅子抹黑豆子", start: 432, time: "12:39"),
]

struct MomentsWidgetTimelineEntry: TimelineEntry {
    let date: Date
    let userList: [UserModel]
    let configuration: ConfigurationIntent
}

struct MomentsWidgetProvider: IntentTimelineProvider {
    
    func placeholder(in context: Context) -> MomentsWidgetTimelineEntry {
        MomentsWidgetTimelineEntry(date: Date(), userList: DEFAULT_USER_LIST, configuration: ConfigurationIntent())
    }
    
    
    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (MomentsWidgetTimelineEntry) -> ()) {
        
        let date = Date()
        let entry: MomentsWidgetTimelineEntry
        
        if context.isPreview {
            entry = MomentsWidgetTimelineEntry(date: date, userList: [], configuration: ConfigurationIntent())
        } else {
            entry = MomentsWidgetTimelineEntry(date: date, userList: DEFAULT_USER_LIST, configuration: ConfigurationIntent())
        }
        
        completion(entry)
    }
    
    
    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
                
        Task {
            
            do {
                
                for i in (0..<DEFAULT_USER_LIST.count) {
                    let tmp_user = DEFAULT_USER_LIST[i]
                    tmp_user.handleImage = try await fetchRemoteImage(urlStr: tmp_user.handle)
                }
                
            } catch {
                print("Request failed with error: \(error)")
            }
            
        }
        

        let entry = MomentsWidgetTimelineEntry(date: Date(), userList: DEFAULT_USER_LIST, configuration: ConfigurationIntent())
        
        let timeline = Timeline(entries: [entry], policy: .never)
        completion(timeline)
    }
    
    func fetchRemoteImage(urlStr: String) async throws -> UIImage? //用来下载互联网上的图片
    {
        guard let url = URL(string: urlStr) else {
            
            return nil
        } //初始化一个字符串常量，作为网络图片的地址
        
        let (data, _) = try await URLSession.shared.data(from: url)
        let image = UIImage(data: data)
        
        return image
    }
}


// 这里就是小组件的UI布局
struct MomentsWidgetEntryView : View {
    
    var entry: MomentsWidgetProvider.Entry
    
    var body: some View {
        VStack(spacing: 0) {
            
            HStack {
                Text("我的好友动态")
                    .font(.system(size: 14, weight: .semibold))
                
                Spacer()
                
                HStack(spacing: 3) {
                    Text("实时更新")
                    
                    Divider()
                        .frame(width: 1, height: 12)
                    
                    Text(Date.formatDateToStr(timeInterval: entry.date.timeIntervalSince1970, dateFormat: "HH:mm"))
                }
                .font(.system(size: 12))
                .foregroundColor(Color.black.opacity(0.5))
                
            }
            
            Divider()
                .foregroundColor(.black.opacity(0.3))
                .frame(height: 1)
                .frame(maxWidth: .infinity)
                .padding(.top, 5)
            
            if entry.userList.isEmpty == true {
                
                ForEach(0..<4) { _ in
                    HStack {
                        Color.black.opacity(0.3)
                            .frame(width: 60, height: 60)
                            .clipShape(RoundedRectangle(cornerRadius: 5))
                        
                        VStack(alignment: .leading) {
                            Color.black.opacity(0.3)
                                .frame(width: 120, height: 24)
                            
                            Color.black.opacity(0.3)
                                .frame(width: 240, height: 24)
                        }
                    }
                    .frame(alignment: .leading)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
                
            } else {
                
                ForEach(0..<entry.userList.count) { i in
                    let user = entry.userList[i]
                    HStack(alignment: .top) {
                        Image(uiImage: user.handleImage ?? UIImage())
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 60, height: 60)
                            .clipShape(RoundedRectangle(cornerRadius: 5))
                        
                        VStack(alignment: .leading, spacing: 5) {
                            HStack(spacing: 3) {
                                Text(user.name)
                                    .font(.system(size: 14, weight: .semibold))
                                
                                Spacer()
                                
                                
                                Label {
                                    Text("\(user.start)")
                                } icon: {
                                    Image(systemName: "heart")
                                        .foregroundColor(.red)
                                }
                                .font(.system(size: 12, weight: .bold))
                                
                            }
                            
                            HStack(alignment: .top) {
                                
                                Text(user.moments)
                                    .font(.system(size: 12, weight: .semibold))
                                    .foregroundColor(.black.opacity(0.6))
//                                    .lineLimit(2)
                                    .frame(maxWidth: .infinity, alignment: .leading)
                                
                                VStack {
                                    Spacer(minLength: 0)
                                    Text("发布于 \(user.time)")
                                        .font(.system(size: 10, weight: .semibold))
                                        .foregroundColor(.black.opacity(0.3))
                                }
                            }
                            
                        }
                        .frame(height: 60, alignment: .top)
                        
                    }
                    .frame(alignment: .leading)
                    .frame(maxHeight: .infinity)
                }
                
            }
            
        }
        .padding(.horizontal, 20)
        .padding(.top, 10)
        //        .padding(.bottom, 5)
        
    }
}

struct MomentsWidget: Widget {
    let kind: String = WidgetType.moments.kind
    
    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: MomentsWidgetProvider()) { entry in
            MomentsWidgetEntryView(entry: entry)
        }
        // 这里定义的就是小组件弹出界面中的标题与副标题
        .configurationDisplayName("好友动态")
        .description("通过该组件可以创建好友动态列表")
        .supportedFamilies([.systemLarge])
    }
}
